package com.xdap.keymen.service.dayang;

import com.alibaba.excel.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.xdap.keymen.entity.dayang.*;
import com.xdap.keymen.utils.OKHttpUtils;
import com.xdap.motor.entity.SnowflakeIdWorker;
import com.xdap.motor.vo.ResponseVo;
import com.xdap.runtime.service.RuntimeAppContextService;
import com.xdap.runtime.service.RuntimeDatasourceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.gson.reflect.TypeToken;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class DaYangProductService extends BaseService {

    private final RuntimeDatasourceService runtimeDatasourceService;
    private final RuntimeAppContextService runtimeAppContextService;
    private final SnowflakeIdWorker snowflakeIdWorker;



    @Autowired
    OKHttpUtils okHttpUtils;
    public ResponseVo getPagingProducts(String productid,String startHour,String endHour) {
        int s=5;
        if (StringUtils.isNotBlank(startHour)) {
            s=Integer.parseInt(startHour);
        }
        int e=0;
        if (StringUtils.isNotBlank(endHour)) {
            e = Integer.parseInt(endHour);
        }
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        ProductsRequest request = new ProductsRequest();
        Map<String, String> params=new HashMap<>();
        params.put("pageNumber", String.valueOf(1));
        params.put("pageSize", String.valueOf(5000));
        if (StringUtils.isNotBlank(productid)) {
            params.put("productid", productid);
        }else{
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            params.put("startDate", LocalDateTime.now().minusHours(s).format(formatter));
            params.put("endDate",LocalDateTime.now().minusHours(e).format(formatter));
        }

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer "+getToken());
        Gson gson = new GsonBuilder().serializeNulls().create();
        //从api接口获取
        String response = okHttpUtils.doGet(getBaseUrl().concat(request.getApiUrl()), params, headers);

        DayangResponse<DyProductTitleResponseEntity> dyResponse = gson.fromJson(response, new TypeToken<DayangResponse<DyProductTitleResponseEntity>>(){}.getType());

        List<DaYangProductTitleEntity> insertProductTitleEntityList = new ArrayList<>();
        List<DaYangProductTitleEntity> updateProductTitleEntityList = new ArrayList<>();

        List<DaYangProductDetailEntity> detailEntityList = new ArrayList<>();
        for (DyProductTitleResponseEntity dyProductTitleResponseEntity:dyResponse.getData()) {
            String documentId;
            //TODO 判断是否存在
            DaYangProductTitleEntity entity= runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId)
                    .eq("productid", dyProductTitleResponseEntity.getProductid())
                    .eq("color", dyProductTitleResponseEntity.getColor())
                    .doQueryFirst(DaYangProductTitleEntity.class);
            if (entity!=null) {
                //TODO 更新
                documentId=entity.getDocumentId();
                DaYangProductTitleEntity updEntity=new DaYangProductTitleEntity();
                updEntity.setId(entity.getId());
                updEntity.setBrands(dyProductTitleResponseEntity.getBrands());
                updEntity.setPclass("[\""+dyProductTitleResponseEntity.getPclass()+"\"]");
                updEntity.setPrice(dyProductTitleResponseEntity.getPrice());
                updEntity.setTitle(dyProductTitleResponseEntity.getTitle()+dyProductTitleResponseEntity.getPrice().intValue()+"元"+dyProductTitleResponseEntity.getProductid()+"#"+dyProductTitleResponseEntity.getColor());
                updateProductTitleEntityList.add(updEntity);
                //TODO 删除子表
                runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId)
                        .eq("tab_doc_id", documentId)
                        .doDelete(DaYangProductDetailEntity.class);

                runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId)
                        .table("dy_product_title")
                        .update("title",dyProductTitleResponseEntity.getTitle()+dyProductTitleResponseEntity.getPrice().intValue()+"元"+dyProductTitleResponseEntity.getProductid()+"#"+dyProductTitleResponseEntity.getColor())
                        .update("price",dyProductTitleResponseEntity.getPrice())
                        .update("class","[\""+dyProductTitleResponseEntity.getPclass()+"\"]")
                        .update("last_update_date", LocalDateTime.now())
                        .eq("id", entity.getId())
                       .doUpdate();
            }else{
                //尺码为空的产品不接收
                if (dyProductTitleResponseEntity.getProductDetails().size()==0) {
                    continue;
                }

                documentId = snowflakeIdWorker.nextId();
                DaYangProductTitleEntity daYangProductTitleEntity =new DaYangProductTitleEntity();
                daYangProductTitleEntity.setId(snowflakeIdWorker.nextId());
                daYangProductTitleEntity.setDocumentId(documentId);
                daYangProductTitleEntity.setProductid(dyProductTitleResponseEntity.getProductid());
                daYangProductTitleEntity.setBrands(dyProductTitleResponseEntity.getBrands());
                daYangProductTitleEntity.setColor(dyProductTitleResponseEntity.getColor());
                daYangProductTitleEntity.setPrice(dyProductTitleResponseEntity.getPrice());
                //sw和sm是定制（sw是女装，sm是男装），其他是成品
                if (dyProductTitleResponseEntity.getProductid().contains("SW")||dyProductTitleResponseEntity.getProductid().contains("SM")) {
                    daYangProductTitleEntity.setProductType("dingzhi");
                }else {
                    daYangProductTitleEntity.setProductType("chengpin");
                }
                //产品属性，默认1
                daYangProductTitleEntity.setProductAttributes("1");
                daYangProductTitleEntity.setProductClassification("zhengjia");
                daYangProductTitleEntity.setProductStatus("qiyong");
                daYangProductTitleEntity.setApplicableStores("[\"101710065973956182016\"]");
                daYangProductTitleEntity.setGender(dyProductTitleResponseEntity.getPtype());
                daYangProductTitleEntity.setPclass("[\""+dyProductTitleResponseEntity.getPclass()+"\"]");
                daYangProductTitleEntity.setTitle(dyProductTitleResponseEntity.getTitle()+dyProductTitleResponseEntity.getPrice().intValue()+"元"+dyProductTitleResponseEntity.getProductid()+"#"+dyProductTitleResponseEntity.getColor());
                insertProductTitleEntityList.add(daYangProductTitleEntity);
            }

            List<DaYangProductDetailEntity> productDetailEntities = dyProductTitleResponseEntity.getProductDetails();
            for (DaYangProductDetailEntity daYangProductDetailEntity :productDetailEntities) {
                daYangProductDetailEntity.setId(snowflakeIdWorker.nextId());
                //子表的tab_doc_id是主表的document_id
                daYangProductDetailEntity.setTabDocId(documentId);
            }
            detailEntityList.addAll(productDetailEntities);
        }

        if(insertProductTitleEntityList.size()>0){
            runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId).doBatchInsert(insertProductTitleEntityList);
        }

        if(detailEntityList.size()>0){
            runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId).doBatchInsert(detailEntityList);
        }

        return ResponseVo.ok();
    }

    /**
     * 推付款订单到新零售系统
     * @param posno
     * @return
     */
    public ResponseVo sendOrder(String posno) {
        String jstr="";
        String databaseName="xdap_app_"+runtimeAppContextService.getCurrentTenantId();
        DaYangOrderTitleEntity entity= runtimeDatasourceService.buildTenantMpaasQuery(databaseName)
                .eq("posno", posno)
                .doQueryFirst(DaYangOrderTitleEntity.class);

        Gson gson = new GsonBuilder().create();
        //jstr="{'orderno': '202505280002','name':'高丰丰','amount': 1900,'orderDate':'2025-06-10 14:56:4'}";
        jstr=gson.toJson(entity);
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer "+getToken());
        //从api接口获取
        String response = okHttpUtils.doPostJson(getBaseUrl().concat("/api/orders"), jstr,headers, MediaType.parse("/"));
        JsonObject dayangResponse=gson.fromJson(response,JsonObject.class);
        if (dayangResponse.get("code").getAsInt()==0) {
            return ResponseVo.ok();
        }else{
            return ResponseVo.error(dayangResponse.get("message").getAsString());
        }
    }

    public ResponseVo getOldOrders(String startDate,String endDate) {
        String jstr="";
        String databaseName="xdap_app_"+runtimeAppContextService.getCurrentTenantId();

        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        params.put("startDate", startDate);
        params.put("endDate",endDate);
        Map<String, String> headers=new HashMap<>();
        //从api接口获取
        //String response = okHttpUtils.doPostJson("http://localhost:25622/JDwebservice.asmx/getOrders", jstr, MediaType.parse("/"));
        String response = okHttpUtils.doGet("http://localhost:25622/JDwebservice.asmx/getOrders", params, headers);
        JsonObject dayangResponse=gson.fromJson(response,JsonObject.class);
        if (dayangResponse.get("code").getAsInt()==0) {
            return ResponseVo.ok();
        }else{
            return ResponseVo.error(dayangResponse.get("message").getAsString());
        }
    }
}
